import { getQuartzList, stopQuartz, startQuartz, executeQuartz, deleteQuartz } from '@/api/quartz'
import { getToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  getQuartzList({ commit }, listQuery) {
    return new Promise((resolve, reject) => {
      getQuartzList(listQuery).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  stopQuartz({ commit }, jobClassName) {
    return new Promise((resolve, reject) => {
      stopQuartz(jobClassName).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  startQuartz({ commit }, jobClassName) {
    return new Promise((resolve, reject) => {
      startQuartz(jobClassName).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  executeQuartz({ commit }, id) {
    return new Promise((resolve, reject) => {
      executeQuartz(id).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  deleteQuartz({ commit }, id) {
    return new Promise((resolve, reject) => {
      deleteQuartz(id).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
